package trunk.firstSec;

// prevent heap bomb in case of hordes of offset results

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class outputStringWrapper {
    public static final int SIZE_LIMIT = 16 * 1024 * 1024;

    private StringBuilder output;
    private static int curChunkIndex = 0;
    private int start, end;
    private boolean sizeExceed = false;

    public outputStringWrapper(){
        output  = new StringBuilder();
        start   = curChunkIndex;
        end     = start;
    }

    public int getFChunkIndex() {return start;}
    public int getLChunkIndex() {return end;}
    public boolean isExceed()   {return sizeExceed;}
    public String getValue()    {return output.toString();}

    public StringBuilder appendOffset(String valueIn){
        PrintWriter print = null;

        if (valueIn.length() + output.length() > SIZE_LIMIT)     // combine and exceed than limit
            try {
                sizeExceed = true;
                // memory dump
                print = new PrintWriter(new FileOutputStream(new File(String.valueOf(curChunkIndex))));
                print.println(output.toString());
                print.flush();

                // set index
                curChunkIndex++;
                end++;

                // make new stuff
                output = new StringBuilder();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (print != null) print.close();
            }
        output.append(',').append(valueIn);
        return output;
    }
}
